package com.wymobilearchitecture.demo.kt


fun main() {

    arrayType()

    collectionType()

    collectionSort()
}

/**
 * 创建数组
 */
fun arrayType() {

    val array1: Array<Int> = arrayOf(1, 2)

    val array2: Array<Int?> = arrayOfNulls<Int>(3)

    //参数是函数并且是最后一个可以写成lamda形式
    val array3: Array<String> = Array(5) { i -> (i * i).toString() }

    //也可以直接指定类型
    val array4 = IntArray(5){45}
    val array5 = intArrayOf(1,2,3)


    //遍历数组
    println("只遍历item")
    for (item in array1) {
        print("$item,")
    }

    println()
    println("只带索引")

    for (i in array1.indices) {
        print("$i ${array1[i]},")
    }

    println()
    println("带索引和item")
    for ((index,item) in array1.withIndex()) {
        print("$index -> $item,")
    }

    println()
    println("forEach")
    array3.forEach { print("$it,") }

    println()
    println("forEach加强")
    array3.forEachIndexed { index, item ->
        print("$index -> $item,")
    }

}

/**
 * 集合
 */
fun collectionType(){

    println()
    println("集合类型")
    //不可变集合
    val stringList : List<String> = listOf("one","two","one")
    //set 集合元素唯一不可重复
    val stringSet : Set<String> = setOf("one","two","one")

    //可变集合
    val numbers : MutableList<Int> = mutableListOf(1,2,3)
    numbers.add(3)
    println("可变集合: $numbers")

    //可变集合set set 集合元素唯一不可重复
    val hello : MutableSet<String> = mutableSetOf("h","e","l","l","o")
    hello.remove("o")
    println(hello)

    //集合的可以进行加减操作
    hello += setOf<String>("w","o","r","d")
    println(hello)

    /**Map<K,V> 不是 Collection 接口的继承者:但是他也是 Kotlin 的一种集合类型*/
    val numberMap : Map<String,Int> = mapOf("key1" to 1,"key2" to 2,"key3" to 3,"key3" to 3,"key4" to 4)
    println("All keys: ${numberMap.keys}")
    println("All values: ${numberMap.values}")

    //判断key或者value是否再map中
    if ("key1" in numberMap.keys) println("判断key或者value是否再map中")
    if (1 in numberMap.values) println("判断key或者value是否再map中")
    if (numberMap.containsKey("key1")) println("判断key或者value是否再map中")

}

/**
 * 集合排序
 */
fun collectionSort(){
    println()
    println("集合排序")
    val numberList : MutableList<Int> = mutableListOf(0,1,2,3)
    //随机排序
    numberList.shuffle()
    println(numberList)
    //从小到大的排序
    numberList.sort()
    println(numberList)
    //从大到小排序
    numberList.sortDescending()
    println(numberList)

    //条件排序
    data class Language(var name:String,var score:Int)
    val languageList : MutableList<Language> = mutableListOf();
    languageList.add(Language("java",80))
    languageList.add(Language("kotlin",90))
    languageList.add(Language("dart",60))
    languageList.add(Language("c",80))
    //单条件排序
    languageList.sortBy { it.score }
    println(languageList)
    //多条件排序
    languageList.sortWith(compareBy({it.score},{it.name}))
    println(languageList)


}

